package com.pospi.pospihold.ui.pay_ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.pospihold.App;
import com.pospi.pospihold.R;
import com.pospi.pospihold.dao.OrderDao;
import com.pospi.pospihold.dialog.WaitingDialog;
import com.pospi.pospihold.dto.OrderDto;
import com.pospi.pospihold.dto.PayBeen;
import com.pospi.pospihold.dto.ReturnDto;
import com.pospi.pospihold.http.LoadServer;
import com.pospi.pospihold.http.UploadData;
import com.pospi.pospihold.print.a920.PrintA920;
import com.pospi.pospihold.ui.CaptureActivity;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.ui.cash_ui.ScanReceiptActivity;
import com.pospi.pospihold.ui.vip_ui.OfflineFavourActivity;
import com.pospi.pospihold.ui.vip_ui.VIPSearchActivity;
import com.pospi.pospihold.util.Api;
import com.pospi.pospihold.util.Constant;
import com.pospi.pospihold.util.DoubleSave;
import com.pospi.pospihold.util.GetData;
import com.pospi.pospihold.util.Model;
import com.pospi.pospihold.util.PareseJson;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayActivity extends BaseActivity {

    @Bind(R.id.tv_vip_favour)
    TextView tvVipFavour;
    @Bind(R.id.tv_offline_favour)
    TextView tvOfflineFavour;
    @Bind(R.id.tv_due1)
    TextView tvDue1;//应收金额1
    @Bind(R.id.iv_cash)
    ImageView ivCash;
    @Bind(R.id.ll_cash)
    LinearLayout llCash;
    @Bind(R.id.iv_bankCard)
    ImageView ivBankCard;
    @Bind(R.id.ll_bankCard)
    LinearLayout llBankCard;
    @Bind(R.id.iv_weiXin)
    ImageView ivWeiXin;
    @Bind(R.id.ll_weiXin)
    LinearLayout llWeiXin;
    @Bind(R.id.iv_alipay)
    ImageView ivAlipay;
    @Bind(R.id.ll_alipay)
    LinearLayout llAlipay;
    @Bind(R.id.iv_integral)
    ImageView ivIntegral;
    @Bind(R.id.ll_integral)
    LinearLayout llIntegral;
    @Bind(R.id.iv_other)
    ImageView ivOther;
    @Bind(R.id.ll_other)
    LinearLayout llOther;
    @Bind(R.id.tv_actual)
    TextView tvActual;//实收金额
    @Bind(R.id.tv_due2)
    TextView tvDue2;//应收金额2
    @Bind(R.id.tv_change)
    TextView tvChange;//找零
    @Bind(R.id.tv_settle)
    TextView tvSettle;
    @Bind(R.id.et_ss)
    EditText etSs;

    private double ysMoney;
    private double zlMoney;
    private double ssMoney;

    private int PayWay;
    private int maxNO;
    private String goodsInfo;
    private String payWayString;
    private String cashier_name;
    private String shopId;

    public final static String PUT_MAXNO = "maxNo";
    public final static String PUT_YS = "ys";
    public final static String PUT_SS = "sss";
    public final static String PUT_ZL = "zl";
    public final static String PUT_PAYWAY = "payway";


    public static final int LAKALA = 444;
    /******
     * 卡支付
     */
    public static final String pay_tp_card = "0";

    /***
     * 扫码支付
     */
    public static final String pay_tp_scan = "1";

    /**
     * 消费
     */
    public static final String proc_cd_spend = "000000";
    /**
     * 消费撤销
     */
    public static final String proc_cd_spend_remove = "200000";
    /**
     * 扫码支付
     */
    public static final String proc_cd_scan = "660000";
    /**
     * 扫码撤销
     */
    public static final String proc_cd_scan_remove = "680000";
    /**
     * 扫码补单
     */
    public static final String proc_cd_scan_budan = "700000";
    /**
     * 结算
     */
    public static final String proc_cd_jiesuan = "900000";
    private String cashier_number;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_pay);
        setTitle("付款");
        ButterKnife.bind(this);
        PayWay = Constant.PAYMENT_CASH;
        payWayString = Constant.PAYMENT_CASH_String;
        ysMoney = DoubleSave.doubleSaveTwo(getIntent().getDoubleExtra(ScanReceiptActivity.PUT_MONEY, 0));
        maxNO = getIntent().getIntExtra(ScanReceiptActivity.PUT_MAXNO, 1606160001);

        tvDue1.setText(String.valueOf(ysMoney));
        tvDue2.setText(String.valueOf(ysMoney));

        init();

        goodsInfo = getSharedPreferences("goodsdto_json", MODE_PRIVATE).getString("json", null);
        int whichOne = getSharedPreferences("islogin", MODE_PRIVATE).getInt("which", 0);
        cashier_name = new PareseJson().parese(
                getSharedPreferences("cashierMsgDtos", MODE_PRIVATE)
                        .getString("cashierMsgDtos", ""))
                .get(whichOne).getName();
        cashier_number = new PareseJson().parese(
                getSharedPreferences("cashierMsgDtos", MODE_PRIVATE)
                        .getString("cashierMsgDtos", ""))
                .get(whichOne).getNumber();

        shopId = getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", "");

    }

    public void init() {
        ssMoney = ysMoney;
        zlMoney = DoubleSave.doubleSaveTwo(ssMoney - ysMoney);
        if (zlMoney >= 0) {
            tvChange.setText(String.valueOf(zlMoney));
        } else {
            showToast("请输入正确的实收金额");
            tvChange.setText("0");
        }
        tvActual.setText(String.valueOf(ssMoney));
    }

    @Override
    protected void onStart() {
        super.onStart();

        etSs.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!etSs.getText().toString().isEmpty()) {
                    ssMoney = DoubleSave.doubleSaveTwo(Double.parseDouble(etSs.getText().toString()));
                    if (ssMoney >= ysMoney) {
                        tvActual.setText(etSs.getText().toString());
                        zlMoney = DoubleSave.doubleSaveTwo(ssMoney - ysMoney);
                        tvChange.setText(String.valueOf(zlMoney));
                    }
                } else {
                    init();
                }
            }
        });

    }

    @OnClick({R.id.tv_vip_favour, R.id.tv_offline_favour, R.id.ll_cash, R.id.ll_bankCard, R.id.ll_weiXin, R.id.ll_alipay, R.id.ll_integral, R.id.ll_other, R.id.tv_settle})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_vip_favour:
                startActivity(VIPSearchActivity.class);
                break;
            case R.id.tv_offline_favour:
                startActivity(OfflineFavourActivity.class);
                break;
            case R.id.ll_cash:
                ivCash.setImageResource(R.drawable.icon_xjl);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_CASH;
                payWayString = Constant.PAYMENT_CASH_String;
                break;
            case R.id.ll_bankCard:
                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_BANK_CARD;
                payWayString = Constant.PAYMENT_BANK_CARD_String;
                break;
            case R.id.ll_weiXin:
                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wxl);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_WEIXIN;
                payWayString = Constant.PAYMENT_WEIXIN_String;
                break;
            case R.id.ll_alipay:
                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfb);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_ALIPAY;
                payWayString = Constant.PAYMENT_ALIPAY_String;
                break;
            case R.id.ll_integral:
                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fk);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_INTEGAL;
                payWayString = Constant.PAYMENT_INTEGAL_String;
                break;
            case R.id.ll_other:
                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qty);
                PayWay = Constant.PAYMENT_OTHER;
                payWayString = Constant.PAYMENT_OTHER_String;
                break;
            case R.id.tv_settle:
                switch (PayWay) {
                    case Constant.PAYMENT_ALIPAY:
//
//                        if (android.os.Build.MODEL.equals(Constant.MODEL_LAKALA)) {
//                            diaoyong(pay_tp_scan, proc_cd_scan);
//                        } else {
                        Intent intent1 = new Intent(PayActivity.this, CaptureActivity.class);
                        startActivityForResult(intent1, Constant.PAYMENT_ALIPAY);
//                        }
                        break;
                    case Constant.PAYMENT_WEIXIN:
//                        if (android.os.Build.MODEL.equals(Constant.MODEL_LAKALA)) {
//                            diaoyong(pay_tp_scan, proc_cd_scan);
//                        } else {
                        Intent intent2 = new Intent(PayActivity.this, CaptureActivity.class);
                        startActivityForResult(intent2, Constant.PAYMENT_WEIXIN);
//                        }
                        break;
                    case Constant.PAYMENT_BANK_CARD:
                        if (android.os.Build.MODEL.equals(Constant.MODEL_LAKALA)) {
                            diaoyong(pay_tp_card, proc_cd_spend);
                        } else {
                            showToast("该功能请等待");
                        }
                        break;
                    default:
                        addOrderToDB(null);
                        Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
                        intent.putExtra(PUT_PAYWAY, payWayString);
                        intent.putExtra(PUT_YS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_ZL, tvChange.getText().toString());
                        intent.putExtra(PUT_SS, tvActual.getText().toString());
                        intent.putExtra(PUT_MAXNO, String.valueOf(maxNO));
                        startActivity(intent);
                        finish();
                        break;

                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String code = null;
        switch (requestCode) {
            case LAKALA:
                switch (resultCode) {
                    //支付成功
                    case Activity.RESULT_OK:
                        addOrderToDB(null);
                        Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
                        intent.putExtra(PUT_PAYWAY, payWayString);
                        intent.putExtra(PUT_YS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_ZL, "0.0");
                        intent.putExtra(PUT_SS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_MAXNO, String.valueOf(maxNO));
                        startActivity(intent);
                        finish();
                        break;
                    // 支付取消
                    case Activity.RESULT_CANCELED:
                        Bundle bundle = data.getExtras();
                        String reason = bundle.getString("reason");
                        if (reason != null) {
                            showToast("支付取消" + reason);
                        }
                        break;
                    case -2:
                        // 交易失败
                        Bundle bundle1 = data.getExtras();
                        String reason1 = bundle1.getString("reason");
                        if (reason1 != null) {
                            showToast(reason1);
                        }
                        break;

                }
                break;
            case Constant.PAYMENT_ALIPAY:
                try {
                    code = data.getStringExtra("code");
                    if (!code.isEmpty()) {
                        requestPay(code, "ali");
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    showToast("支付失败，未获取到条形码");
                }

                break;
            case Constant.PAYMENT_WEIXIN:
                try {
                    code = data.getStringExtra("code");
                    if (!code.isEmpty()) {
                        requestPay(code, "wx");
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    showToast("支付失败，未获取到条形码");
                }
                break;
        }
    }

    /**
     * 开始调用拉卡拉支付
     *
     * @param pay_tp
     * @param proc_cd
     */

    public void diaoyong(String pay_tp, String proc_cd) {
        try {
            ComponentName componet = new ComponentName("com.lkl.cloudpos.payment", "com.lkl.cloudpos.payment.activity.MainMenuActivity");
            Intent intent = new Intent();
            intent.setComponent(componet);
            Bundle bundle = new Bundle();
            bundle.putString("msg_tp", "0200");//固定值，请求
            bundle.putString("pay_tp", pay_tp);//0是银行卡，1是扫码
            bundle.putString("proc_tp", "00");//00代表是消费
            bundle.putString("proc_cd", proc_cd);//交易处理码
            bundle.putString("amt", String.valueOf(ysMoney));//金额
            bundle.putString("order_no", String.valueOf(maxNO));//订单号
            bundle.putString("appid", this.getPackageName());//调用者应用包名
            bundle.putString("time_stamp", GetData.getYYMMDDHHMMSSNoSpellingTime());//得到现在的时间
            bundle.putString("order_info", "扫码支付");//订单的信息
            intent.putExtras(bundle);
            this.startActivityForResult(intent, LAKALA);
        } catch (ActivityNotFoundException
                e) {
            //TODO:
        } catch (Exception e) {
            //TODO
        }
    }

    /**
     * 请求支付
     *
     * @param barcode 条形码
     * @param way     传送给服务器的支付方式
     * @param name    支付成功后告诉用户的支付方式
     */
    private String out_trade_no = null;

    public void requestPay(String barcode, final String way) {
        //得到现在进行请求的是支付宝还是微信
        showDialog("正在请求支付");

        SharedPreferences preferences = getSharedPreferences("Token", MODE_PRIVATE);
        String aa = preferences.getString("value", "");
        String[] names = aa.split("\\,");
        String deviceNo = names[2];//收银机号
        String user_Id = names[3];//用户ID
        String ServerNo = names[4];//服务器号
        String uid = names[1];

        String now = GetData.getHHmmssTime();
        Log.i("获取到的当前时间", now);
        out_trade_no = String.valueOf(maxNO) + deviceNo + now + user_Id + ServerNo;//交易号
        Log.i("out_trade_no", out_trade_no);

        RequestParams payParamsMaps = new RequestParams();
        payParamsMaps.put("auth_code", barcode);//扫描到的条形码数据
        payParamsMaps.put("body", "统销商品自定义价格");//死数据
        payParamsMaps.put("pay_mode", way);//支付方式,支付宝或者是微信
        payParamsMaps.put("fee", getPayMoney(way));//订单的金额
        payParamsMaps.put("out_trade_no", out_trade_no);//交易号
        payParamsMaps.put("uid", uid);//用户的id
        Log.i("pay", payParamsMaps.toString());

        AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("onSuccess", new String(bytes));

                ReturnDto returnDto = new ReturnDto();

                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    returnDto.setResult(object.getInt("Result"));
                    returnDto.setMessage(object.getString("Message"));
                    returnDto.setValue(String.valueOf(object.getString("Value")));
                    closeDialog();
                    if (returnDto.getResult() == 1) {
                        addOrderToDB(returnDto.getValue());
                        Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
                        intent.putExtra(PUT_PAYWAY, payWayString);
                        intent.putExtra(PUT_YS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_ZL, "0.0");
                        intent.putExtra(PUT_SS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_MAXNO, String.valueOf(maxNO));
                        startActivity(intent);
                        finish();
                    } else {
                        showToast(returnDto.getMessage());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                ReturnDto returnDto = new ReturnDto();

                closeDialog();
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    returnDto.setResult(object.getInt("Result"));
                    returnDto.setMessage(object.getString("Message"));
                    returnDto.setValue(String.valueOf(object.getInt("Value")));
                    closeDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("请求失败，请稍后重试");
                }
            }
        };
        LoadServer.getConnect(getApplicationContext(), Api.PAYMENT, payParamsMaps, handler);
    }

    public String getPayMoney(String way) {
        String payMoney = null;

        if (way.equals("wx")) {
            payMoney = String.valueOf((int) (ysMoney * 100));
        } else if (way.equals("ali")) {
            payMoney = String.valueOf(ysMoney);
        }
        return payMoney;
    }

    private Dialog waitingDialog;

    public void showDialog(String msg) {
        if (waitingDialog == null) {
            waitingDialog = WaitingDialog.createLoadingDialog(this, msg);
            waitingDialog.show();
        }
    }

    public void closeDialog() {
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
    }

    public void addOrderToDB(String aliPayNumber) {
        final OrderDto orderDto = new OrderDto();
        orderDto.setOrder_info(goodsInfo);//存储的该订单的商品的信息
        orderDto.setPayway(payWayString);
        orderDto.setTime(GetData.getYYMMDDTime());
        orderDto.setSs_money(ssMoney);
        orderDto.setYs_money(ysMoney);
        orderDto.setZl_money(zlMoney);
        orderDto.setCashiername(cashier_name);
        orderDto.setCashiernumber(cashier_number);
        orderDto.setShop_id(shopId);
        orderDto.setOrderType(Constant.ORDERTYPE_SALE);
        orderDto.setMaxNo(maxNO);
        orderDto.setSearchTime(GetData.getSearchTime());
        Log.i("GetData.getSearchTime()", "" + GetData.getSearchTime());
        orderDto.setCheckoutTime(GetData.getDataTime());
        orderDto.setDetailTime(GetData.getHHmmssTimet());
        orderDto.setHasReturnGoods(Constant.hasReturnGoods_No);
        orderDto.setOut_trade_no(out_trade_no);
        orderDto.setPayReturn(aliPayNumber);
        orderDto.setIfFinishOrder(Constant.YES);
        /**
         * 给数据库里面添加一条记录
         */
        PayBeen payBeen = new PayBeen();
//        RequestParams params = UploadData.getUpData(getApplicationContext(), orderDto);

        new OrderDao(getApplicationContext()).addOrder(orderDto);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                if (App.IsPrinter) {// 如果打印机可用
//                    if (Build.MODEL.equals(Model.A920)) {
//                        PrintA920.prnVoucher(getApplicationContext(), orderDto);
//                    }
//                }
//            }
//        }).start();
    }
}
